package com.hmall.search.mq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.ItemDTO;
import com.hmall.common.msg.UpOrDownMsg;
import com.hmall.search.service.ISearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ItemListener {

    @Autowired
    private ISearchService searchService;

    @Autowired
    private ObjectMapper mapper;

//    /**
//     * 监听上架商品
//     */
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = "up100"),
//            exchange = @Exchange(name = "item100.upordown", type = ExchangeTypes.TOPIC),
//            key = "key.up100"
//    ))
//    public void up(ItemDTO itemDTO){
//        searchService.createItem(itemDTO);
//    }
//
//    /**
//     * 监听下架商品
//     */
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = "down100"),
//            exchange = @Exchange(name = "item100.upordown", type = ExchangeTypes.TOPIC),
//            key = "key.down100"
//    ))
//    public void down(ItemDTO itemDTO){
//        searchService.deleteItem(itemDTO);
//    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "queue.upordown"),
            exchange = @Exchange(name = "item100.upordown2", type = ExchangeTypes.TOPIC),
            key = "key"
    ))
    public void upOrDown(String msg){
        UpOrDownMsg upOrDownMsg = null;
        try {
            upOrDownMsg = mapper.readValue(msg, UpOrDownMsg.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if (upOrDownMsg.getStatus() == null){
            throw new RuntimeException("参数异常！");
        }
        if (upOrDownMsg.getStatus() == 1){
            //上架
            searchService.createItem(upOrDownMsg.getItemDTO());
        }else if (upOrDownMsg.getStatus() == 2){
            //下架
            searchService.deleteItem(upOrDownMsg.getItemDTO());
        }else {
            throw new RuntimeException("参数异常！");
        }
    }
}
